<?php

class Users extends Controller
{
	function Users()
	{
		parent::Controller();

		// Load auth config file
		$this->config->load('auth');
		$auth = $this->config->item('auth');

		foreach($auth as $key => $value)
		{
			$this->$key = $value;
		}
		$this->output->enable_profiler(TRUE);
	}

	function register()
	{
		if($this->auth->logged_in())
		{
			redirect(base_url());
		}
		else
		{
			$this->load->library('form_validation');

			$this->form_validation->set_error_delimiters('<span id="error_message" class="error_message">', '</span>');

			// Set rules for the registration form
			$this->form_validation->set_rules('first_name', 'first name', 'trim|required|max_length[40]|xss_clean');
			$this->form_validation->set_rules('last_name', 'last_name', 'trim|required|max_length[40]|xss_clean');
			$this->form_validation->set_rules('email', 'email', 'trim|required|max_length[50]|valid_email|matches[confirm_email]|callback_email_check');
			$this->form_validation->set_rules('confirm_email', 'confirm_email', 'trim|required|max_length[50]|valid_email');
			$this->form_validation->set_rules('password', 'password', 'required|min_length[6]|max_length[20]|matches[confirm_password]');
			$this->form_validation->set_rules('confirm_password', 'confirm password', 'required');

			if($this->form_validation->run() == FALSE)
			{
				$header['js'] = array(
						'users/register.js'
				);
				$this->template->build('users/auth/register','',$header);
			}
			else
			{
				$auth = $this->auth->register(
						$this->input->post('email'),
						$this->input->post('password'),
						$this->input->post('first_name'),
						$this->input->post('last_name')
				);

				switch($auth)
				{
					case 'REGISTRATION_SUCCESS':
						$this->template->build('users/auth/success');
						break;
					case 'REGISTRATION_SUCCESS_EMAIL':
						$data['email'] = $this->input->post('email');
						$this->template->build('users/auth/email_sent', $data);
						break;
					case false:
					// Don't know when and how this will produce a false but
					// better to leave it here just in case
						break;
				}
			}
		}
	}

	function email_check($email)
	{
		// Checks if the email exists - this function is called from the set of
		// rules of the registration form
		if($this->db->get_where($this->users_table, array('email' => $email), '1')->num_rows() > 0)
		{
			// Display this error
			$this->form_validation->set_message('email_check', 'This email is already registered');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}

	function login()
	{
		if($this->auth->logged_in())
		{
			redirect(base_url());
		}
		else
		{
			$this->load->library('form_validation');

			// Set rules for the login form
			$this->form_validation->set_rules('email', 'email', 'trim|required|max_length[50]|valid_email');
			$this->form_validation->set_rules('password', 'password', 'required|min_length[6]|max_length[20]');

			// Check if the form validation was passed
			if($this->form_validation->run() == FALSE)
			{
				// this determines the status messages if a login was previously
				// submitted
				$status = $this->session->flashdata('status');

				$data['status_message'] = ''; // defines status message
				if($status == 'NOT_ACTIVATED')
				{
					// grab the flashed data from previously submitted logins
					$masked_user_id = $this->session->flashdata('masked_user_id');
					$not_activated_key = $this->session->flashdata('not_activated_key');

					// generate link to email activation key again
					$email_activation_link = base_url().'users/email_activation/'.$masked_user_id.'/'.$not_activated_key;

					// set the status message
					$data['status_message'] = 'Your email has not been activated.
						If you want to resend your activation email, click <a href="'.$email_activation_link.'">here</a>.';
				}
				elseif($status == 'ACTIVATION_EMAIL_SENT')
				{
					$data['status_message'] = 'Your activation email has been resent.';
				}
				elseif($status == 'BANNED')
				{
					$data['status_message'] = $this->session->flashdata('reason');
				}
				elseif($status == 'WRONG_EMAIL_PASSWORD')
				{
					$data['status_message'] = 'The email or password you have entered is incorrect';
				}

				$this->template->build('users/auth/login',$data);
			}
			else
			{
				$auth = $this->auth->login($this->input->post('email'),$this->input->post('password'));

				if($auth['status'] === 'BANNED')
				{
					$flashdata = array(
							'status' => $auth['status'],
							'reason' => $auth['reason']
					);
					$this->session->set_flashdata($flashdata);
					redirect(base_url().'users/login');
				}
				elseif($auth['status'] === 'NOT_ACTIVATED')
				{
					// grabs the key and masked user ID to be used in creating
					// the link to resend the activation email
					$flashdata = array(
							'status' => $auth['status'],
							'masked_user_id' => $auth['masked_user_id'],
							'not_activated_key' => $auth['not_activated_key']
					);
					$this->session->set_flashdata($flashdata);
					redirect(base_url().'users/login');
				}
				elseif($auth['status'] === FALSE)
				{
					$this->session->set_flashdata('status', 'WRONG_EMAIL_PASSWORD');
					redirect(base_url().'users/login');
				}
				elseif($auth['status'] === TRUE)
				{
					redirect(base_url());
				}
			}
		}

	}

	function resend_activation()
	{
		$user_id = $this->uri->segment(3);

		$this->auth->resend_activation_email($user_id);

		$data['message'] = 'Your activation email has been sent';

		$this->template->build('blank', $data);
	}

	function profile()
	{
		// Only account owners can access this
		if($this->auth->logged_in())
		{
			// Loads the date language file to help display the timezone name
			// of the user
			$this->lang->load('date');

			// Grab the user's data based on his user ID
			$data['user'] = $this->auth->get_user($this->session->userdata('id'));

			$data['dashboard_message'] = $this->session->flashdata('dashboard_message');

			$this->template->build('users/auth/profile', $data);
		}
		else
		{
			redirect(base_url().'users/login');
		}
	}

	function edit_profile()
	{
		// Only account owners can access this
		if(!$this->auth->logged_in())
		{
			redirect(base_url().'users/login');
		}
		else
		{
			$this->load->library('form_validation');

			// Set the rules for the user edit form
			$this->form_validation->set_rules('first_name', 'first name', 'trim|required|max_length[40]|xss_clean');
			$this->form_validation->set_rules('last_name', 'last_name', 'trim|required|max_length[40]|xss_clean');

			if($this->form_validation->run() == FALSE)
			{
				// Grab the user's data based on his user ID
				$data['user'] = $this->auth->get_user($this->session->userdata('id'));

				// Get the countries dropdown menu
				$data['countries'] = $this->auth->get_countries_dropdown();

				$this->template->build('users/auth/edit_profile', $data);
			}
			else
			{
				// Grab user id from the userdata session
				$user_id = $this->session->userdata('id');

				// Update the user's data

				$user_data = array(
						'first_name' => $this->input->post('first_name'),
						'last_name' => $this->input->post('last_name'),
						'country_id' => $this->input->post('country_id'),
						'timezone' => $this->input->post('timezones')
				);

				$this->auth->update_user($user_id, $user_data);

				// set user dashboard message
				$this->session->set_flashdata('dashboard_message', 'Your profile has been updated');

				// Redirect to the user edit form page
				redirect(base_url().'users/profile/');
			}
		}
	}

	function logout()
	{
		$this->auth->logout();
		$this->template->build('users/auth/logged_out');
	}

	function view()
	{
		// This function is only available to admin users
		if(!$this->auth->admin_logged_in())
		{
			redirect(base_url().'admin/login');
		}
		else
		{
			// Loads the table pagination library
			$this->load->library('pagination');

			$header['title'] = 'Assassin8 | View Users';
			$header['css'] = array(
					'table-style.css',
					'admin/admin_users.css'
			);
			$header['js'] = array(
					'admin/admin_users.js'
			);

			// Get pagination variables
			// If there is no uri segment 3, then this is page 0
			if($this->uri->segment(3) != '')
				$page = $this->uri->segment(3);
			else
				$page = 0;

			// Pagination config
			$config['per_page'] = '10';
			$config['base_url'] = base_url().'admin/users/';
			$config['total_rows'] = $this->auth->get_users_total();

			$this->pagination->initialize($config);

			$data['users'] = $this->auth->get_users_page($page, $config['per_page']);
			$data['pagination_links'] = $this->pagination->create_links();

			// message
			$data['message'] = $this->session->flashdata('message');

			$this->template->build('users/admin/view',$data,$header,'',$this->config->item('site_admin_template'));
		}
	}

	function edit()
	{
		// This is only available to admin users

		if(!$this->auth->admin_logged_in())
		{
			redirect(base_url().'admin/login');
		}
		else
		{
			$this->load->library('form_validation');

			// Set the rules for the user edit form
			$this->form_validation->set_rules('first_name', 'first name', 'trim|required|max_length[40]|xss_clean');
			$this->form_validation->set_rules('last_name', 'last_name', 'trim|required|max_length[40]|xss_clean');
			$this->form_validation->set_rules('email', 'email', 'trim|required|max_length[50]|valid_email');

			if($this->form_validation->run() == FALSE)
			{
				$user_id = $this->uri->segment(3);

				$data['user'] = $this->auth->get_user($user_id);

				$data['groups'] = $this->auth->get_groups_dropdown();

				$data['countries'] = $this->auth->get_countries_dropdown();

				$data['ban_history'] = $this->auth->get_ban_history($user_id);

				$this->template->build('users/admin/edit',$data,'','',$this->config->item('site_admin_template'));
			}
			else
			{
				$user_id = $this->input->post('user_id');

				// Update the user's data
				$user_data = array(
						'first_name' => $this->input->post('first_name'),
						'last_name' => $this->input->post('last_name'),
						'email' => $this->input->post('email'),
						'group_id' => $this->input->post('group_id'),
						'country_id' => $this->input->post('country_id'),
						'timezone' => $this->input->post('timezones')
				);

				$this->auth->update_user($user_id, $user_data);

				// set message for viewing in users/view
				$this->session->set_flashdata('message', 'The user has been updated');

				// Redirect to the user edit form page
				redirect(base_url().'users/view/');
			}

		}
	}

	function update_email_check($email)
	{
		// This will check if the newly entered email is already in the database
		// or not.

		// @TODO: check if email already exists if user decides to change his/her email
	}

	function change_password()
	{
		// Only account owners can access this
		if(!$this->auth->logged_in())
		{
			redirect(base_url());
		}
		else
		{
			$this->load->library('form_validation');

			$this->form_validation->set_error_delimiters('<span class="page_error">', '</span>');
			$this->form_validation->set_rules('old_password', 'required|max_length[20]');
			$this->form_validation->set_rules('new_password', 'password', 'required|min_length[6]|max_length[20]|matches[confirm_new_password]');
			$this->form_validation->set_rules('confirm_new_password', 'confirm password', 'required');

			if($this->form_validation->run() == FALSE)
			{
				$data['error_message'] = $this->session->flashdata('error_message');
				$this->template->build('users/auth/change_password',$data);
			}
			else
			{
				if( ! $this->auth->change_password($this->input->post('old_password'),$this->input->post('new_password')))
				{
					redirect(base_url().'users/change_password');
				}
				else
					redirect(base_url().'users/profile');
			}
		}
	}

	function ban()
	{
		// This is available to admin users only
		if(!$this->auth->admin_logged_in())
		{
			redirect(base_url().'admin/login');
		}
		else
		{
			if(!$this->uri->segment(3))
			{
				redirect(base_url().'users/view');
			}
			else
			{
				$this->load->library('form_validation');

				$this->form_validation->set_rules('reason', 'trim|required|max_length[100]|xss_clean');

				if($this->form_validation->run() == FALSE)
				{
					$user_id = $this->uri->segment(3);
					$data['user'] = $this->auth->get_user($user_id);
					$this->template->build('users/auth/ban', $data,'','',$this->config->item('site_admin_template'));
				}
				else
				{
					$this->auth->ban_user($this->input->post('user_id'), $this->input->post('reason'));
					redirect(base_url().'users/view');
				}
			}
		}
	}

	function unban()
	{
		if(!$this->auth->admin_logged_in())
		{
			show_404();
		}
		else
		{
			$user_id = $this->uri->segment(3);
			$this->auth->unban_user($user_id);
			redirect('users/view');
		}
	}

	function add()
	{
		// Only admin can access this
		if(!$this->auth->admin_logged_in())
		{
			redirect(base_url().'admin/no_permission');
		}
		else
		{
			$this->load->library('form_validation');

			// Add user rules
			$this->form_validation->set_rules('first_name', 'first name', 'trim|required|max_length[40]|xss_clean');
			$this->form_validation->set_rules('last_name', 'last_name', 'trim|required|max_length[40]|xss_clean');
			$this->form_validation->set_rules('email', 'email', 'trim|required|max_length[50]|valid_email|matches[confirm_email]|callback_email_check');
			$this->form_validation->set_rules('confirm_email', 'confirm_email', 'trim|required|max_length[50]|valid_email');
			$this->form_validation->set_rules('password', 'password', 'required|min_length[6]|max_length[20]|matches[confirm_password]');
			$this->form_validation->set_rules('confirm_password', 'confirm password', 'required');

			if($this->form_validation->run() == FALSE)
			{
				$data['groups'] = $this->auth->get_groups_dropdown();
				$this->template->build('users/admin/add', $data,'','',$this->config->item('site_admin_template'));
			}
			else
			{
				$auth = $this->auth->admin_register(
						$this->input->post('email'),
						$this->input->post('password'),
						$this->input->post('first_name'),
						$this->input->post('last_name'),
						$this->input->post('group_id'),
						$this->input->post('activate')
				);

				switch($auth)
				{
					case 'REGISTRATION_SUCCESS':
						$this->template->build('users/auth/success','','','',$this->config->item('site_admin_template'));
						break;
					case 'REGISTRATION_SUCCESS_EMAIL':
						$data['email'] = $this->input->post('email');
						$this->template->build('users/auth/email_sent', $data,'','',$this->config->item('site_admin_template'));
						break;
					case false:
					// Don't know when and how this will produce a false but
					// better to leave it here just in case
						break;
				}
			}
		}
	}

	function activate()
	{
		if($this->uri->segment(3) != FALSE)
		{
			$activation_code = $this->uri->segment(3);
			if( ! $this->auth->activate($activation_code))
			{
				$data['message'] = 'This is an invalid activation code';
				$this->template->build('blank', $data);
			}
			else
			{
				if($this->uri->segment(4) == 'admin')
				{
					redirect(base_url().'users/view');
				}
				else
					$this->template->build('users/auth/activation_success');
			}
		}
		else
			show_404();
	}

	function email_activation()
	{
		if($this->uri->segment(3) && $this->uri->segment(4))
		{
			$masked_user_id = $this->uri->segment(3);
			$not_activated_key = $this->uri->segment(4);

			// email activation code
			if($this->auth->email_activation_code($masked_user_id,$not_activated_key))
			{
				// if successful, redirect to login page with flashed data
				$this->session->set_flashdata('status', 'ACTIVATION_EMAIL_SENT');
				redirect(base_url().'users/login');
			}
			else
			{
				// this means that either the email does not exist or the key given
				// was invalid - this is basically a restricted page for visitors
				// so we show them the 404 error
				show_404();
			}
		}
		else
			show_404();

	}

	function delete()
	{
		// only admin users can access this page
		if(!$this->auth->admin_logged_in())
		{
			// show 404 restricted page
			show_404();
		}
		else
		{
			if( ! $this->uri->segment(3))
				show_404();
			else
			{
				if($this->auth->delete_user($user_id))
					redirect(base_url().'users/view/');
				else
					show_404();
			}
		}
	}

	function forgot_password()
	{
		// if the user is logged in, he cannot access this page
		if($this->auth->logged_in())
		{
			redirect(base_url());
		}
		else
		{
			$this->load->library('form_validation');

			$this->form_validation->set_error_delimiters('<span class="error_message">', '</span>');

			// Add user rules
			$this->form_validation->set_rules('email', 'email', 'trim|required|max_length[50]|valid_email');

			if($this->form_validation->run() == FALSE)
			{
				$data['message'] = $this->session->flashdata('forgot_password_message');
				$this->template->build('users/auth/forgot_password');
			}
			else
			{
				$email = $this->input->post('email');

				$password_reset = $this->auth->confirm_password_reset($email);

				if($password_reset)
				{
					$data['heading'] = 'An email has been sent to '.$email;
					$data['message'] = 'You will need to click on the link sent to your email to reset your password.';
					$this->template->build('users/message', $data);
				}
				else
				{
					$this->session->set_flashdata('forgot_password_message', 'No user with that email exists');
					redirect(base_url().'users/forgot_password');
				}
			}
		}
	}

	function reset_password()
	{
		if(!$this->uri->segment(3) && !$this->uri->segment(4))
		{
			show_404();
		}
		else
		{
			$masked_user_id = $this->uri->segment(3);
			$forgotten_password_code = $this->uri->segment(4);

			if($this->auth->reset_password($masked_user_id,$forgotten_password_code))
			{
				$data['heading'] = 'Your password has been reset';
				$data['message'] = 'Please check your email for your new password.';

				$this->template->build('users/message', $data);
			}
			else
			{
				show_404();
			}
		}
	}
}

?>
